package main;

import game.Game;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.image.MemoryImageSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import javax.swing.JDesktopPane;
import javax.swing.JFrame;
import javax.swing.JInternalFrame;
import javax.swing.Timer;
import quicktime.*;
import quicktime.std.movies.Movie;
import quicktime.app.view.QTFactory;
import quicktime.io.*;

/*
 * InstructionMovie.java
 *
 * Created on May 13, 2009, 9:28:56 AM
 */

/**
 *
 * @author Vinay
 */
public class InstructionMovie extends JInternalFrame {

    static File movieFile;
    static Movie m;
    static Game g = new Game();

	MouseListener listener;

    int secs, timeTaken=0;
    Timer time = new Timer(1000, new TimeListener());

    /** Creates new form InstructionMovie */
    public InstructionMovie(String game) {
       /// super();
        super("",
              false, //resizable
              false, //closable
              false, //maximizable
              false);//iconifiable

        javax.swing.plaf.InternalFrameUI ui = this.getUI();
        ((javax.swing.plaf.basic.BasicInternalFrameUI)ui).setNorthPane(null);

        initComponents();
        this.setVisible(true);

		listener = new InstructionMovie.CheckMouse();
		g.runner.getGlassPane().addMouseListener (listener);

		hideMouse();

        boolean ready = initMov(game);
        if (ready)
            startMov();
        else {
            movieNameLabel.setText ("Video not available.");
            secs = 2;
            time.start();
        }
    }

    private void hideMouse() {
        int[] pixels = new int[16 * 16];
        Image image = Toolkit.getDefaultToolkit().createImage(new MemoryImageSource(16, 16, pixels, 0, 16));
        Cursor transparentCursor = Toolkit.getDefaultToolkit().createCustomCursor(image, new Point(0, 0), "invisibleCursor");
        g.runner.setCursor(transparentCursor);
		g.runner.getGlassPane().setVisible(true);
		g.runner.getGlassPane().setCursor(transparentCursor);
    }

	class CheckMouse implements MouseListener {
		public void mousePressed(MouseEvent e) { hideMouse(); }
        public void mouseReleased(MouseEvent e) {}
        public void mouseEntered(MouseEvent e) { hideMouse(); }
        public void mouseExited(MouseEvent e) { hideMouse(); }
        public void mouseClicked(MouseEvent e) {
		}
	}

    /**
     * Initializes variables.
     *
     * @param game The game whose video we want to load.
     * @return Whether or not the video exists.
     */
    public boolean initMov(String game) {
        try {
//        InputStream is;
//        is = this.getClass().getResourceAsStream("/movies/"+game+".mov");
//        if(is == null)
//            is = this.getClass().getResourceAsStream("/movies/filler.mov");
            Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();

            if (g.debugMode)
                movieNameLabel.setText(game);
            
            File f;
            f = new File("movies/"+game+".mov");
            System.err.println ("[DEBUG]: Instruction movie title is " + game
				+ ".mov, exists=" + f.exists());
            if(!f.exists()) {
                f = new File("movies/filler.mov");
                if (!f.exists())
                    return false;
            }
			else {
				movieNameLabel.setText (game);
			}
            FileInputStream is = new FileInputStream(f);
            movieFile=toFile(is);

            return true;
        }
        catch(Exception ex) {
            ex.printStackTrace();
            g.logError(ex);
            return false;
        }
    }

    public static File toFile(FileInputStream is) {
	try {
            File f=new File("outFile.java");
            OutputStream out=new FileOutputStream(f);
            byte buf[]=new byte[1024];
            int len;
            while((len=is.read(buf)) > 0)
		out.write(buf,0,len);
            out.close();
            is.close();
            return f;
	}
        catch(Exception e) {
            e.printStackTrace();
            g.logError(e);
        }
        return null;
    }

    public void startMov() {
        try {
            QTSession.open();
            OpenMovieFile omf=OpenMovieFile.asRead(new QTFile(movieFile));
            m=Movie.fromFile(omf);
            Component c=QTFactory.makeQTComponent(m).asComponent();

            c.setPreferredSize(new Dimension(400,300));
            this.pnlMov.add(BorderLayout.CENTER,c);
            pnlMov.setVisible(true);
            c.setVisible(true);

            m.start();
            secs=m.getDuration()/3000;
            time.start();
        }
        catch(QTException e1) {
            System.err.println("[ERROR]: Got a QuickTime exception");
            e1.printStackTrace();
            g.logError(e1);
        }
    }

    class TimeListener implements ActionListener {
    	public void actionPerformed(ActionEvent e) {
    		secs--;
            if(secs>=0) {

            }
            if(secs==0) {
                //time.stop();
                lblNote.setText("Loading ...");
            }
            if(secs==-4) {
                time.stop();
                try {
					g.runner.getGlassPane().removeMouseListener(listener);
					g.runner.getGlassPane().setVisible(false);
                    setVisible(false);
                    g.free=true;
                } catch(Exception ex) {
                    ex.printStackTrace();
                    g.logError(ex);
                }
            }
    	}

    }

    public static void main(String args[]) {
        JFrame main = new JFrame();
        JDesktopPane dPane = new JDesktopPane();
        InstructionMovie frame = new InstructionMovie("");
        main.setSize(820, 620);
        dPane.add(frame);
        main.add(dPane);
        main.setVisible(true);
        dPane.setVisible(true);
        frame.setVisible(true);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlMov = new javax.swing.JPanel();
        movieNameLabel = new javax.swing.JLabel();
        lblNote = new javax.swing.JLabel();

        setBackground(new java.awt.Color(255, 255, 255));
        setBorder(null);
        setPreferredSize(new java.awt.Dimension(800, 600));

        pnlMov.setBorder(javax.swing.BorderFactory.createMatteBorder(25, 25, 25, 25, new java.awt.Color(0, 0, 0)));
        pnlMov.setLayout(new java.awt.BorderLayout());

        movieNameLabel.setFont(new java.awt.Font("Tahoma", 0, 24));
        movieNameLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        movieNameLabel.setText("filler");
        pnlMov.add(movieNameLabel, java.awt.BorderLayout.PAGE_START);

        lblNote.setBackground(new java.awt.Color(255, 255, 255));
        lblNote.setFont(new java.awt.Font("Calibri", 1, 24));
        lblNote.setForeground(new java.awt.Color(51, 102, 255));
        lblNote.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(pnlMov, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 800, Short.MAX_VALUE)
            .add(layout.createSequentialGroup()
                .add(10, 10, 10)
                .add(lblNote, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup()
                .add(pnlMov, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 503, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(lblNote, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 54, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel lblNote;
    private javax.swing.JLabel movieNameLabel;
    private javax.swing.JPanel pnlMov;
    // End of variables declaration//GEN-END:variables

}
